<template>
    <div>
        <div class="card" style="margin-bottom: 5px;">
            <el-input clearable @clear="load" style="width: 240px;margin-right: 10px;" v-model="data.search.topId" placeholder="请输入类别查询" :prefix-icon="Search"  @keyup.enter="load"></el-input>
            <el-input clearable @clear="load" style="width: 240px;margin-right: 10px;" v-model="data.search.preId" placeholder="请输入字典前缀查询" :prefix-icon="Search"  @keyup.enter="load"></el-input>
            <el-input clearable @clear="load" style="width: 240px;margin-right: 10px;" v-model="data.search.name" placeholder="请输入名称查询" :prefix-icon="Search"  @keyup.enter="load"></el-input>
            <el-button type="primary" style="margin-left: 20px;" @click="load">查 询</el-button>
            <el-button @click="reset">重 置</el-button>
        </div>
        <div class="card" style="margin-bottom: 5px;">
            <el-button type="primary" @click="handleAdd">新 增</el-button>
            <el-button type="success" @click="switchBatch">批量切换是否生效</el-button>
            <el-button type="danger" @click="deleteBatch">批量删除</el-button>
        </div>
        <div class="card" style="margin-bottom: 5px;">
            <el-table :data="data.tableData" style="width: 100%;" 
                :header-cell-style="{color: '#333',backgroundColor: '#eaf4ff',alignItems: 'center'}"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="dictTopId" label="字典类别"/>
                <el-table-column prop="dictId" label="字典Id"/>
                <el-table-column prop="dictName" label="字典名称"/>
                <el-table-column prop="isDeleted" label="是否生效">
                    <template #default="scope">
                        <el-switch
                            v-model="scope.row.switch"
                            @click="switchActive(scope.row.id)"
                            class="ml-2"
                            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        />
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100"> 
                    <template #default="scope">
                    <el-button type="primary" icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
                    <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="card" style="margin-bottom: 5px;">
            <el-pagination
                v-model:current-page="data.paginationData.pageNum"
                v-model:page-size="data.paginationData.pageSize"
                :page-sizes="[5, 10, 15, 20]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="data.paginationData.total"
                @change="load"
            />
        </div>
        <el-dialog v-model="data.addDialogparams.dialogVisible" title="字典管理" width="40%"  destroy-on-close>
            <el-form :model="data.addDialogparams.form" label-width="80" style="padding: 20px 30px 10px 0;">
                <el-form-item prop="dictTopId" label="字典类别">
                    <el-input v-model="data.addDialogparams.form.dictTopId" autocomplete="off" placeholder="请输入字典类别（可以是中文英文）"/>
                </el-form-item>
                <el-form-item prop="dictId" label="字典id">
                    <el-input v-model="data.addDialogparams.form.dictId" autocomplete="off" placeholder="请输入字典id"/>
                </el-form-item>
                <el-form-item prop="dictName" label="字典名称">
                    <el-input v-model="data.addDialogparams.form.dictName" autocomplete="off" placeholder="请输入字典名称"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                <el-button @click="data.addDialogparams.dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="save">
                    保存
                </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>

import { Search} from '@element-plus/icons-vue';
import request from '@/utils/request';
import { getConfig } from '@/utils/config'; 
import { ElMessage } from 'element-plus';
import {formatDateTime,beforeUpload,} from '@/utils/function'
import '@wangeditor/editor/dist/css/style.css' // 引入css
import { onBeforeUnmount,ref,reactive,shallowRef,onMounted  } from 'vue';
import { Editor,Toolbar} from '@wangeditor/editor-for-vue'
import { useUserStore } from '@/store/user';


const userStore = useUserStore()
const data = reactive({
    user: userStore.getUser(),
    search: {
        id: null,
        title: null,
        content: null
    },
    paginationData: {
        pageNum: 1,
        pageSize: 5,
        total: 0
    },
    tableData: [],
    addDialogparams: {
        dialogVisible: false,
        form: {}
    },
    multipleSelectionvalue:[]

})

const load = () => {
    request.get('/dict/page',{
        params: {
            pageNum: data.paginationData.pageNum,
            pageSize: data.paginationData.pageSize,
            topId: data.search.topId,
            preId: data.search.preId,
            name: data.search.name
        }
    }).then(res => {
        if(res.code === '200') {
            // data.tableData = res.data.list;
            data.tableData = res.data.list.map(item => {
                return {
                    ...item,
                    // 添加switch  字段
                    switch: ref(item.isActive == 0)
                };
            });
            data.paginationData.total = res.data.total;
        }else {
            ElMessage.error(res.msg)
        }
    }) 
}
load()

const reset = () => {
    data.search = {}
    load()
}

const handleAdd = () => {
  data.addDialogparams.dialogVisible = true
  data.addDialogparams.form = {}

}

const switchBatch = () => {
    if (data.multipleSelectionvalue.length === 0) {
        ElMessage.warning('请选择需要转换的数据')
        return
    }
    const param = data.multipleSelectionvalue.map(item => {
        return item.id
    })
    request.post('/dict/switchactive/batch', param).then(res => {
        if (res.code === '200') {
            ElMessage.success("批量转换成功")
            load()
        } else {
            ElMessage.error(res.msg)
        }
    })

}

const deleteBatch = () => {
    if (data.multipleSelectionvalue.length === 0) {
        ElMessage.warning('请选择需要删除的数据')
        return
    }
    ElMessageBox.confirm(
        '删除后无法恢复，您确认删除所选数据吗?',
        '删除确认',
        {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        }
    ).then(res => {
        const param = data.multipleSelectionvalue.map(item => {
            return item.id
        })
        console.log(param);
        request.delete('/dict/batch', {data:param}).then(res => {
            if (res.code === '200') {
                ElMessage.success("批量删除成功")
                load()
            } else {
                ElMessage.error(res.msg)
            }
        })
    })
}

const handleSelectionChange = (rows) => {   //  rows是实际选择的数组
  data.multipleSelectionvalue = rows
}

const handleEdit = (row) => {
    data.addDialogparams.form = JSON.parse(JSON.stringify(row))
    data.addDialogparams.dialogVisible = true
}

const del = (id) => {
    ElMessageBox.confirm(
        '删除后无法恢复，您确认删除所选数据吗?',
        '删除确认',
        {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        }
    ).then(res => {
        request.delete('/dict/' + id).then(res => {
            if (res.code === '200') {
                ElMessage.success("删除成功")
                load()
            } else {
                ElMessage.error(res.msg);
            }
        })
    })

}

const save = () => {
  data.addDialogparams.form.id ? update() : add()
}

const update = () => {
    request.put('/dict',{
        id: data.addDialogparams.form.id,
        dictTopId: data.addDialogparams.form.dictTopId,
        dictId: data.addDialogparams.form.dictId,
        dictName: data.addDialogparams.form.dictName,
    }).then(res => {
        if (res.code === '200') {
            ElMessage.success("修改成功")
            load()
        } else {
            ElMessage.error(res.msg);
        }
        data.addDialogparams.dialogVisible = false
    })
}


const add = () => {
    request.post('/dict',{
        dictTopId: data.addDialogparams.form.dictTopId,
        dictId: data.addDialogparams.form.dictId,
        dictName: data.addDialogparams.form.dictName,
        createId: data.user.id,
        createTime: new Date()
    }).then(res => {
        if (res.code === '200') {
            ElMessage.success("新增成功")
            load()
        } else {
            ElMessage.error(res.msg);
        }
        data.addDialogparams.dialogVisible = false
    })
}

const switchActive = (id) => {
    request.post('/dict/switchactive/' + id).then(res => {
        if (res.code === '200') {
            ElMessage.success("转换成功")
            load()
        } else {
            ElMessage.error(res.msg)
        }
    })

}
</script>